#!/bin/bash


AppName=books-manage-java-1.0.0.jar
MAIN_CLASS=io.dbw.ServerApplication
#环境变量
environment=test
if [[ "$MAIN_CLASS" == "com.yourpackage.YourMainClass" ]]; then
    echo "请先修改 MAIN_CLASS 的值为你自己项目启动Class，然后再执行此脚本。"
	exit 0
fi

#JVM参数
#JVM_OPTS="-Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512M -Xmx512M -XX:PermSize=256M -XX:MaxPermSize=512M -XX:+HeapDumpOnOutOfMemoryError #-XX:+PrintGCDateStamps  -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC -XX:+UseParallelOldGC"
APP_BASE_PATH=$(cd `dirname $0`; pwd)
APP_HOME=`pwd`
DATE=`date +%F`
CP=${APP_BASE_PATH}/config:${APP_BASE_PATH}/lib/*

if [ "$1" = "" ];
then
    echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
    exit 1
fi

if [ "$AppName" = "" ];
then
    echo -e "\033[0;31m 未输入应用名 \033[0m"
    exit 1
fi

function start()
{
    PID=`ps -ef |grep java|grep $AppName|grep -v grep|awk '{print $2}'`

	if [ x"$PID" != x"" ]; then
	    echo "$AppName is running..."
	else
		 nohup java -Xverify:none ${JVM_OPTS} -cp ${CP} ${MAIN_CLASS} --spring.profiles.active=${environment} >/dev/null 2> /dev/null &
		
		echo "Start $AppName success..."
	fi
}


function stop()
{
    # 支持集群部署
    kill `pgrep -f ${APP_BASE_PATH}` 2>/dev/null

    # kill 命令不使用 -9 参数时，会回调 onStop() 方法，确定不需要此回调建议使用 -9 参数
    # kill `pgrep -f ${MAIN_CLASS}` 2>/dev/null

    # 以下代码与上述代码等价
    # kill $(pgrep -f ${MAIN_CLASS}) 2>/dev/null
	echo "$AppName already stopped."
}
function restart()
{
    stop
    sleep 2
    start
}

function status()
{
    PID=`ps -ef |grep java|grep $MAIN_CLASS|grep -v grep|wc -l`
    if [ $PID != 0 ];then
        echo "$MAIN_CLASS is running..."
    else
        echo "$MAIN_CLASS is not running..."
    fi
}

case $1 in
    start)
    start;;
    stop)
    stop;;
    restart)
    restart;;
    status)
    status;;
    *)

esac
